package com.mibus.mibusmobile;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.IOException;
import java.net.InetAddress;
import java.util.List;


public class RequestPost extends AsyncTask <String,Integer,String>{
    private List<NameValuePair> postContent;
    private Context context;

    public RequestPost(List<NameValuePair> postContent, Context context){
        this.postContent = postContent;
        this.context = context;

    }
    @Override
    protected String doInBackground(String... url) {
        /*HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
        HttpConnectionParams.setSoTimeout(httpParameters, 10000);*/

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url[0]);
        String result = "NoInternet";
        if(checkOnlineState()) {
            try {
                httppost.setEntity(new UrlEncodedFormEntity(postContent));
                HttpResponse response = httpClient.execute(httppost);
                HttpEntity entity = response.getEntity();
                result = JSONParser.inputStreamToString(entity.getContent()).toString();
                postContent.clear();
            } catch (Exception e) {
                Log.i("Hubo un problema", e.toString());
            }
            return result;
        }else{
            return "NoInternet";
        }
    }

    public boolean checkOnlineState() {
        ConnectivityManager CManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo NInfo = CManager.getActiveNetworkInfo();
        if (NInfo != null && NInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }
}
